package com.example.myapplication;

import static android.location.LocationManager.NETWORK_PROVIDER;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.Adapter.RecyclerAdapter;
import com.example.myapplication.bean.Weather15DayBean;
import com.example.myapplication.bean.WeatherBean;
import com.example.myapplication.untils.HttpUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class MainActivity extends AppCompatActivity {
    ExecutorService es = Executors.newCachedThreadPool();

    private WeatherBean weatherBean;
    private ImageView imageView2;
    private TextView TvCondition;
    private TextView TvTemp;
    private TextView TvTip;
    private LocationManager locationManager;
    private String provider;
    private String cityNam;
    private String lat = "23.127191";
    private String lon = "113.355747";
    private TextView TvOn;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        es.submit(new NetImageHandler());

        Thread imageViewHander = new Thread(new NetImageHandler());
        ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 5, 1000, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));

        executor.execute(imageViewHander);
        initView();


        //获取定位服务
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //获取当前可用的位置控制器
        List<String> list = locationManager.getProviders(true);
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (list.contains(LocationManager.GPS_PROVIDER)) {
            //是否为GPS位置控制器
            provider = LocationManager.GPS_PROVIDER;
        } else if (list.contains(NETWORK_PROVIDER)) {
            //是否为网络位置控制器
            provider = NETWORK_PROVIDER;

        } else {
            Toast.makeText(this, "请检查网络或GPS是否打开",
                    Toast.LENGTH_LONG).show();
            return;
        }
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

//        Location location = locationManager.getLastKnownLocation(provider);
        Location location = locationManager.getLastKnownLocation(NETWORK_PROVIDER);

        TvOn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (location != null) {
                    //获取当前位置，这里只用到了经纬度
                    String string = "纬度为：" + location.getLatitude() + ",经度为："
                            + location.getLongitude();
                    System.out.println("纬度为：" + location.getLatitude());
                    System.out.println(",经度为：" + location.getLongitude());

                    lon = String.valueOf(location.getLongitude());
                    lat = String.valueOf(location.getLatitude());

                }
                Thread imageViewHander = new Thread(new NetImageHandler());
                imageViewHander.start();

            }
        });
//        if (location != null) {
//            //获取当前位置，这里只用到了经纬度
//            String string = "纬度为：" + location.getLatitude() + ",经度为："
//                    + location.getLongitude();
//            System.out.println("纬度为：" + location.getLatitude());
//            System.out.println(",经度为：" + location.getLongitude());
//        }


        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager.requestLocationUpdates(provider, 2000, 2,
                locationListener);

    }

    LocationListener locationListener = new LocationListener() {

        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderDisabled(String arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onLocationChanged(Location arg0) {
            // TODO Auto-generated method stub
            // 更新当前经纬度
        }
    };

    //关闭时解除监听器
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (locationManager != null) {
            locationManager.removeUpdates(locationListener);
        }
    }


    private void initView() {
        imageView2 = (ImageView) findViewById(R.id.imageView2);
        TvCondition = (TextView) findViewById(R.id.Tv_condition);
        TvTemp = (TextView) findViewById(R.id.Tv_temp);
        TvTip = (TextView) findViewById(R.id.Tv_tip);
        TvOn = (TextView) findViewById(R.id.Tv_on);
    }

    class NetImageHandler implements Runnable {
        @Override
        public void run() {
            try {
                HttpUtils httpUtils = new HttpUtils();
                HashMap<String, String> map = new HashMap<>();

                map.put("Authorization", "APPCODE bc70323d41644bad991822fe3748476c");
                String s = httpUtils.postJson("http://aliv8.data.moji.com/whapi/json/aliweather/condition?lat=" + lat + "&lon=" + lon, map, null);

                JSONObject jsonObject = JSONUtil.parseObj(s);
                Object data = jsonObject.getByPath("data.condition");
                cityNam = (String) jsonObject.getByPath("data.city.name");
                Gson gson = new Gson();
                String json = gson.toJson(data);
                weatherBean = gson.fromJson(json, WeatherBean.class);//获取返回结果字符串


                ArrayList<Weather15DayBean> weather15DayBeans = getWeather15DayBeans(httpUtils,map);
                weatherBean.setWeather15DayBeans(weather15DayBeans);

                //发送消息，通知UI组件显示图片
                handler.sendEmptyMessage(0);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @NonNull
    private ArrayList<Weather15DayBean> getWeather15DayBeans(HttpUtils httpUtils, HashMap<String, String> map) throws IOException {
        String s = httpUtils.postJson("http://aliv8.data.moji.com/whapi/json/aliweather/forecast15days?lat="+lat +"&lon=" +lon, map, null);
        JSONObject jsonObject = JSONUtil.parseObj(s);
        Object data = jsonObject.getByPath("data.forecast");
        Gson gson = new Gson();

        String json = gson.toJson(data);

        JsonParser parser = new JsonParser();
        JsonArray jsonArray = parser.parse(json).getAsJsonArray();
        ArrayList<Weather15DayBean> list = new ArrayList<>();
        for (JsonElement jsonElement : jsonArray) {
            Weather15DayBean weather15DayBean = gson.fromJson(jsonElement, Weather15DayBean.class);
            list.add(weather15DayBean);
        }
        list.subList(0, 2).clear();
        list.subList(3, list.size()).clear();
        return list;
    }
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                show();
            }
        }


    };


    private void show() {
        TvOn.setText(cityNam);
        TvCondition.setText(weatherBean.getCondition());
        TvTemp.setText(weatherBean.getTemp()+"°C");
        TvTip.setText(weatherBean.getTips());
        int imageResource = getResources().getIdentifier("@drawable/ic" + weatherBean.getIcon(), null, getPackageName());
        Drawable res = getResources().getDrawable(imageResource);
        imageView2.setImageDrawable(res);


        RecyclerView recyclerView = findViewById(R.id.rv_successive_dynasties_weather);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
        recyclerView.setLayoutManager(linearLayoutManager);
        ArrayList<WeatherBean> list = new ArrayList<>();
        list.add(weatherBean);
        RecyclerAdapter recyclerAdapter = new RecyclerAdapter(list);
        recyclerView.setAdapter(recyclerAdapter);

    }


}



